package com.ruoyi.wx.config;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import com.google.common.collect.Maps;
import com.ruoyi.wx.domain.WxMpApp;
import com.ruoyi.wx.service.IWxMpAppService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;

@Configuration
public class WxMpConfiguration {
	
	private static Map<String, WxMpService> mpServices = Maps.newHashMap();

    public static Map<String, WxMpService> getMpServices() {
        return mpServices;
    }
	
	@Autowired
	private IWxMpAppService wxMpAppService;

	@PostConstruct
    public void initServices() {
        final List<WxMpApp> configs = wxMpAppService.list();
        if (configs == null) {
            throw new RuntimeException("没有配置公众号信息！");
        }
        
        mpServices = configs.stream().map(a -> {
        	WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
            configStorage.setAppId(a.getAppId());
            configStorage.setSecret(a.getAppSecret());
            configStorage.setToken(a.getToken());

            WxMpService service = new WxMpServiceImpl();
            service.setWxMpConfigStorage(configStorage);
            return service;
        }).collect(Collectors.toMap(s -> s.getWxMpConfigStorage().getAppId(), a -> a, (o, n) -> o));
    }
	
}
